using System.Drawing;
using Microsoft.Extensions.Caching.Distributed;
using net_work.Common;
using net_work.Common.Request;
using net_work.Data.Enum.Sys;
using net_work.Data.Enum.System;
using net_work.Data.POCO.Sys;
using net_work.IService.BackgroundTask.IService;
using OfficeOpenXml;
using TaskStatus = net_work.Data.Enum.System.TaskStatus;

namespace net_work.Service.BackgroundTask.Service;

public class TcrAndStuExcelService(ITaskQueue taskQueue, IDistributedCache cache) : ITcrAndStuExcelService
{
    public async Task<string> CreateTask(IFormFile file, TaskType taskType)
    {
        // 创建 TaskExcelFiles 目录（如果不存在的话）
        var directoryPath = Path.Combine(Directory.GetCurrentDirectory(), "TaskExcelFiles");
        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        // 生成文件路径
        var filePath = Path.Combine(directoryPath, file.FileName);

        // 保存文件到磁盘
        await using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }

        var task = new TaskRequest
        {
            TaskId = Guid.NewGuid().ToString(),
            TaskType = taskType,
            Parameters = new Dictionary<TaskParams, object>
            {
                { TaskParams.FilePath, filePath },
                { TaskParams.FileName, file.FileName },
                { TaskParams.FileSize, file.Length },
                { TaskParams.FileType, file.ContentType }
            },
            Status = TaskStatus.Pending
        };
        await cache.SetStringAsync("Task:" + task.TaskId, task.Status.ToString(),
            new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2) });

        await taskQueue.EnqueueAsync(task);

        return task.TaskId;
    }

    public byte[] TeacherExport()
    {
        return GetTemplate("教师导入模版", TeacherExcelCells.TipMessages, TeacherExcelCells.HeaderColumns);
    }

    public byte[] StudentExport()
    {
        return GetTemplate("学生导入模版", StudentExcelCells.TipMessages, StudentExcelCells.HeaderColumns);
    }

    public async Task<string> GetTaskStatus(string taskId)
    {
        var stringAsync = await cache.GetStringAsync("Task:" + taskId);
        if (stringAsync == null)
        {
            return "任务已过期";
        }

        if (!Enum.TryParse<TaskStatus>(stringAsync, out var parsedStatus))
        {
            return "未知的任务状态";
        }

        return parsedStatus switch
        {
            TaskStatus.Pending => "任务正在等待处理",
            TaskStatus.Completed => "任务已完成",
            TaskStatus.Processing => "任务正在处理中",
            TaskStatus.Failed => "任务处理失败",
            _ => "未知的任务状态"
        };
    }

    private byte[] GetTemplate(string name, List<(string message, ExcelCellColor color)> tips,
        List<(string message, ExcelCellColor color)> headerColumns)
    {
        using var package = new ExcelPackage();
        var worksheet = package.Workbook.Worksheets.Add(name);

        // 处理提示信息
        var currentRow = 1; // 初始行号
        foreach (var (message, color) in tips)
        {
            worksheet.Cells[$"A{currentRow}"].Value = message;
            worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Merge = true; // 合并单元格
            worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Bold = true; // 加粗
            worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Size = 20; // 设置字体大小

            // 设置颜色
            switch (color)
            {
                case ExcelCellColor.Red:
                    worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Color.SetColor(Color.Red);
                    break;
                case ExcelCellColor.Blue:
                    worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Color.SetColor(Color.Blue);
                    break;
                case ExcelCellColor.Yellow:
                    worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Color.SetColor(Color.Yellow);
                    break;
                case ExcelCellColor.Green:
                    worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Color.SetColor(Color.Green);
                    break;
                case ExcelCellColor.Black:
                default:
                    worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.Font.Color.SetColor(Color.Black);
                    break;
            }

            worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.HorizontalAlignment =
                OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            worksheet.Cells[$"A{currentRow}:Z{currentRow}"].Style.VerticalAlignment =
                OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

            currentRow++; // 下一行
        }

        // 表头行：提示信息结束后加两行空行，再插入表头
        currentRow += 2; // 增加两行空行

        // 设置表头列并直接设置颜色
        for (var i = 0; i < headerColumns.Count; i++)
        {
            var (columnHeader, color) = headerColumns[i];
            var cell = worksheet.Cells[$"{(char)('A' + i)}{currentRow}"];
            cell.Value = columnHeader;

            // 设置颜色
            switch (color)
            {
                case ExcelCellColor.Red:
                    cell.Style.Font.Color.SetColor(Color.Red);
                    break;
                case ExcelCellColor.Blue:
                    cell.Style.Font.Color.SetColor(Color.Blue);
                    break;
                case ExcelCellColor.Yellow:
                    cell.Style.Font.Color.SetColor(Color.Yellow);
                    break;
                case ExcelCellColor.Green:
                    cell.Style.Font.Color.SetColor(Color.Green);
                    break;
                case ExcelCellColor.Black:
                default:
                    cell.Style.Font.Color.SetColor(Color.Black);
                    break;
            }
        }

        // 设置表头样式
        using (var range = worksheet.Cells[$"A{currentRow}:Z{currentRow}"])
        {
            range.Style.Font.Bold = true;
            range.Style.Font.Size = 14;
            range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            range.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
        }

        // 自动调整列宽
        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

        // 生成模板的字节数组
        return package.GetAsByteArray();
    }
}